import { Component } from '@angular/core';

import {Events, AlertController, NavController, NavParams } from 'ionic-angular';

import { MarketingWeeklyEditService } from './edit.service';

import { MarketingDailyListService } from '../../daily/list/list.service';

import { Common } from '../../../../providers/common';

import { Storage } from '@ionic/storage';

import _ from 'lodash';

import {MarketingDailyListPage} from "../../daily/list/list.component";

@Component({
  selector: 'page-marketing-weekly-edit',
  templateUrl: './edit.html',
  providers: [MarketingWeeklyEditService,MarketingDailyListService]
})
export class MarketingWeeklyEditPage {
	moa_page_name: any = "page-marketing-weekly-edit";
  moa_page_explain: any = "";

  //工作周报对象
  edit = null;
  //工作日报列表
  chanelList = null;
  //可以选择的最大日期
  maxDate = "";
  maxEndDate = "";
  //结束日期可以选择的最小日期
  minEndDate = "2015-01-01";

  //用户信息
  userInfo:any = [];

  //编辑模式 0：新增，1：修改
  editmode = 0;
  //
  indexAuthority = '0';
  //标题
  title:string = "";

  pageShow5 = "";
  pageShow6 = "";
  pageShow7 = "";

  constructor(
    public alertCtrl: AlertController,
    public navCtrl: NavController,
    private navParams: NavParams,
    public editService: MarketingWeeklyEditService,
    public common: Common,
    public events: Events,
    public storage: Storage,
    public dailyService : MarketingDailyListService
    ) {

    //可以选择的日期不能超过今天
    this.maxDate = this.common.getDate(7);
    this.maxEndDate = this.common.getNowFormatDate();

    //获取详细页面链接过来的数据
    this.edit = this.navParams.get("edit");

    this.editmode = this.navParams.get("editmode") ? this.navParams.get("editmode") : 0;

    this.title = this.editmode == 0 ? "新增工作周报":"修改工作周报";

    this.moa_page_explain = this.title;

    if (this.editmode != 0 && this.edit) {
      this.pageShow5 = this.edit[5];
      this.pageShow6 = this.edit[6];
      this.pageShow7 = this.edit[7];
    }

    this.events.unsubscribe('weekly-edit-lis:update');
    // 监听是否有更新
    this.events.subscribe('weekly-edit-list:update', (dataList) => {
      console.info('---- list--weekly-edit-lis:update------');
      console.log(dataList);
      let that = this;
      if(that.chanelList){
        //判斷記錄是否已經存在
         _.forEach(dataList,function(item){
             if(!_.find(that.chanelList,{'1':item[1]})){
                that.chanelList.push(item);
             }
         });
      }else{
        this.chanelList = dataList;
      }
      //this.chanelList = this.chanelList ? _.concat(this.chanelList, dataList) : dataList;;
    });
    //获取用户信息
    this.storage.get('userInfo').then((userInfo) => {
      if (userInfo) {
        this.userInfo = userInfo;
      }
    });
    this.storage.get('indexAuthority').then((data) => {
      this.indexAuthority = data ? data["vc_type"] : '0';
    });
    this.initData();
  }

  /**
   * [initData 初始化工作日报数据]
   * @param {[type]} item [参数]
   */
   initData(){
     if(this.editmode == 1){
       //修改
       this.editService.getChanelListData(this.edit[0]).subscribe(data => {
         var dataList = [];
         _.forEach(data, function (i) {
           let d = i.split("|");
           d.push(false);
           d.push("false");
           dataList.push(d);
         });
         this.chanelList = this.chanelList ? _.concat(this.chanelList, dataList) : dataList;
       });
     }

     if(this.editmode == 0 && !this.edit){
       //新增
       this.edit = new Array(8);
       this.edit[1] = this.editService.getFirstDayOfWeek(1);
       this.edit[2] = this.editService.getFirstDayOfWeek(7);
       this.endDateChange();
     }
   }

  clickEnable = true;
   /**
   * [save 保存修改记录]
   */
   save(){
     this.edit[5] = this.pageShow5;
     this.edit[6] = this.pageShow6;
     this.edit[7] = this.pageShow7;

     let that = this;
     if(!this.checkForm()){
       return ;
     }

     if (!this.clickEnable) {
       return;
     } else {
       this.clickEnable = false;
     }

     //获取工作日报id
     let communtionids = [];
     _(this.chanelList).forEach(function(item) {
       communtionids.push(item[1]);
     })
     console.log('communtionids');
     console.log(communtionids);
     this.edit[8] = _(communtionids).toString();
     if (this.edit[5]) {
       this.edit[5] = this.edit[5].replace(/\r{0,}\n/g, "<br/>");
       this.edit[5] = this.edit[5].replace(/\n{0,}\r/g, "<br/>");
       // this.edit[5] = this.edit[5].replace(/\s/g, "<nbsp>");
     }
     if (this.edit[6]) {
       this.edit[6] = this.edit[6].replace(/\r{0,}\n/g, "<br/>");
       this.edit[6] = this.edit[6].replace(/\n{0,}\r/g, "<br/>");
       // this.edit[6] = this.edit[6].replace(/\s/g, "<nbsp>");
     }
     if (this.edit[7]) {
       this.edit[7] = this.edit[7].replace(/\r{0,}\n/g, "<br/>");
       this.edit[7] = this.edit[7].replace(/\n{0,}\r/g, "<br/>");
       // this.edit[7] = this.edit[7].replace(/\s/g, "<nbsp>");
     }

     this.editService.saveWeekly(this.indexAuthority,this.editmode,this.edit,this.userInfo).subscribe(data => {
       let msg = _.startsWith(data,'0') ? "保存成功" :data;
       console.log('保存之后KSB返回数据：');
       console.log(data);

       this.edit[5] = this.edit[5].replace("/\<nbsp\>/g", " ");
       this.edit[6] = this.edit[6].replace("/\<nbsp\>/g", " ");
       this.edit[7] = this.edit[7].replace("/\<nbsp\>/g", " ");

       console.log(this.edit[5]);

       if (data) {
         let alert = this.alertCtrl.create({
           title: "提示",
           message: msg,
           buttons: [
             {
               text: "确定",
               role: 'cancel',
               handler: () => {
                 if (this.editmode == 0) {
                   if (_.startsWith(data, '0')) {
                     that.edit[0] = data[0].split('|')[1];
                     that.events.publish('weekly-list:update', that.edit);
                   }
                 } else {
                   that.events.publish('weekly-edit:update', that.edit, that.chanelList);
                   that.events.publish('weekly-list:update', that.edit);
                 }
                 this.navCtrl.pop();
               }
             }
           ]
         });
         alert.present();
       } else {
         this.clickEnable = true;
       }

     });

     setTimeout(function () {
       that.clickEnable = true;
     }, 2000);
   }
   /*
   *检查表单是否填写完整
   */
   checkForm(){
     // 构建时间，如：2017-03-06 15:00:00
     let startTime = this.edit[1] + " 12:00:00";
     let endTime = this.edit[2] + " 12:00:00";
     let msg = "";
     if (startTime > endTime) {
       msg ="起始日期不能大于结束日期.";
     }
     let startDate = this.edit[1].replace(/-/g,'');
     let endDate = this.edit[2].replace(/-/g,'');

     //判断结束日期是否在同一周
     console.log(startDate + '所在周日期:' + this.editService.getCurrentWeek(startDate));
     /*let index = _.indexOf(this.editService.getCurrentWeek(startDate),endDate);
     if (index == -1) {
       //&& this.editService.getFirstDayOfWeek(this.edit[2],7) >= this.edit[2]
       msg ="起始日期和结束日期不在同一周.";
     }*/
     if(!this.edit[4] || this.edit[4].length == 0 ){
       msg ="标题内容不能为空.";
     }
     console.log(_.size(this.edit[5]));
     if(_.size(this.edit[5]) >= 1500 || _.size(this.edit[6]) >= 1500 || _.size(this.edit[7]) >= 1500){
       msg ="总结、计划、建议的长度不能大于3000.";
     }
     if(msg != ""){
       let alert = this.alertCtrl.create({
         title: "提示",
         message: msg,
         buttons: [
         {
           text: '确定',
           role: 'cancel',
           handler: () => {
             //console.log('Cancel clicked');
           }
         }
         ]
       });
       alert.present();
       return false;
     }else{
       return  true;
     }
 }
   /*
   * 添加工作日报，从工作日报列表中选择
   */
   addCommunication(){
     this.navCtrl.push(MarketingDailyListPage, { "showCheck":true});
   }
   /*
   * 取消关联
   */
   delCommunication(){
     _.remove(this.chanelList, function(item) {
       return item[9] === true;
     });
   }
   checkIsSelected(item) {
     item[item.length - 1] = !item[item.length - 1];
   }

  /*
  *设置结束日期的最小可选日期等于起始日期
  */
  startDateChange(){
    this.minEndDate = this.edit[1];
    console.log(this.editService.getCurrentWeek(this.edit[1].replace(/-/g,'')));
    this.endDateChange();
  }
  /*
  *根据日期自动生成标题
  */
  endDateChange(){
    let that = this;
    let startDate = this.edit[1].replace(/-/g,'');
    let endDate = this.edit[2].replace(/-/g,'');
    this.getDailyList();
    //判断结束日期是否在同一周
    /*let index = _.indexOf(this.editService.getCurrentWeek(startDate),endDate);
    if (index == -1) {
      let msg ="起始日期和结束日期必须在同一周，请重新选择。";
      let alert = this.alertCtrl.create({
        title: "提示",
        message: msg,
        buttons: [
        {
          text: '确定',
          role: 'cancel',
          handler: () => {
            let lastday = _.last(this.editService.getCurrentWeek(startDate));
            let y = lastday.substr(0,4);
            let m = lastday.substr(4,2);
            let d = lastday.substr(6,2);
            this.edit[2] = `${y}-${m}-${d}`;
            this.maxEndDate = this.edit[2];
            this.minEndDate = this.edit[1];
            this.getDailyList();
          }
        }
        ]
      });
      alert.present();
    }else{
      this.getDailyList();
    }*/
  }

  getDailyList(){
    let weeks = this.editService.getWeekOfMonth(this.edit[1]);
    let startDate = this.edit[1].replace(/-/g,'');
    let endDate = this.edit[2].replace(/-/g,'');
    this.storage.get('userInfo').then((userInfo) => {
      if (userInfo) {
        this.userInfo = userInfo;
        this.edit[4] = `[${this.userInfo.emname}][第${weeks}周][${startDate}至${endDate}]`;

        //新增查询关联的工作日报
        if(this.editmode == 0){
          let queryCondition = {
            "emp" : "'" + userInfo.emname + "'",
            "cusname":"",
            "startdate" : startDate,
            "enddate" : endDate
          }
          this.dailyService.getListData(1, queryCondition).subscribe(data => {
            if (data) {
              var dataList = [];
              _.forEach(data, function (i) {
                let d = i.split("|");
                d[9] = false;
                dataList.push(d);
              });
              this.chanelList = dataList;
            }
          })
        }
      }
    });
  }
}
